package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.openai.models.responses.Response;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.config.properties.HuaWeiIotConfigProperties;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import com.zzyl.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.stream.Collectors;

/**
 * deviceService业务层处理
 *
 * @author ruoyi
 * @date 2025-10-23
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private HuaWeiIotConfigProperties huaWeiIotConfigProperties;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IoTDAClient client;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 查询device
     *
     * @param id device主键
     * @return device
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询device列表
     *
     * @param device device
     * @return device
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 从物联网同步产品列表
     */
    @Override
    public void syncProductList() {
        //对接华为云Api，获取产品列表
        ListProductsResponse response = client.listProducts(new ListProductsRequest());
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("同步产品列表异常");
        }
        //将获取到的产品列表转为json字符串传入redis
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_KEY, JSONUtil.toJsonStr(response.getProducts()));
    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //从Redis查询产品列表JSON字符串
        String productJsonList = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_KEY);
        if (StrUtil.isBlank(productJsonList)) {
            return Collections.emptyList();
        }
        //解析JSON为产品列表
        List<ProductSummary> productList = JSONUtil.toList(productJsonList, ProductSummary.class);
        //遍历产品列表，转为前端需要的数据类型
        List<ProductVo> collect = productList.stream().map(x -> {
            return ProductVo.builder()
                    .productKey(x.getProductId())
                    .productName(x.getName())
                    .build();
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 注册设备
     *
     * @param dto
     */
    @Override
    @Transactional
    public void register(DeviceDto dto) {
        //用雪花算法。当做唯一标识码
        String nodeId = IdUtil.getSnowflakeNextIdStr();
        //设备备注名称
        String deviceDescription = dto.getRegisterDeviceRequest().getNickname();
        //设备名称是否重复
        Long count = this.lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()).count();
        if (count > 0) {
            throw new BaseException("设备重复，请重新添加");
        }
        //设备标识是否重复
        Long countNodeId = this.lambdaQuery().eq(Device::getNodeId, nodeId).count();
        if (countNodeId > 0) {
            throw new BaseException("设备重复，请重新添加");
        }
        //同一位置是否绑定了相同的产品
        Long countLocation = this.lambdaQuery()
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getProductKey, dto.getProductKey())
                .count();
        if (countLocation > 0) {
            throw new BaseException("当前位置绑定过相同类型的产品");
        }
        //注册设备到华为云IOT平台
        AddDeviceRequest addDeviceRequest = new AddDeviceRequest();
        AddDevice addDevice = new AddDevice();
        addDevice.setProductId(dto.getProductKey());
        addDevice.setDeviceName(dto.getDeviceName());
        addDevice.setDescription(deviceDescription);

        addDevice.setNodeId(nodeId);

        AuthInfo authInfo = new AuthInfo();
        //uuid当唯一秘钥
        String secret = IdUtil.simpleUUID();
        authInfo.setSecret(secret);
        addDevice.setAuthInfo(authInfo);

        addDeviceRequest.setBody(addDevice);
        AddDeviceResponse response = client.addDevice(addDeviceRequest);
        //响应201则代表成功
        if (response.getHttpStatusCode() != HttpStatus.CREATED) {
            throw new BaseException("注册到华为云失败");
        }

        //保存设备到表中
        Device device = new Device();
        BeanUtils.copyProperties(dto, device);
        device.setNodeId(nodeId);
        device.setIotId(response.getDeviceId());
        device.setNickname(deviceDescription);
        device.setDeviceDescription(deviceDescription);
        device.setSecret(secret);

        String productName = this.getProductNameFromCache(dto.getProductKey());
        device.setProductName(productName);
        this.save(device);

    }

    /**
     * 从缓存中根据id获取名称
     *
     * @param productAppId
     * @return
     */
    private String getProductNameFromCache(String productAppId) {
        //从redis中查询
        String productListJson = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_KEY);
        if (StringUtils.isBlank(productListJson)) {
            return null;
        }

        //解析
        List<ProductSummary> productList = JSONUtil.toList(productListJson, ProductSummary.class);
        ProductSummary product = productList.stream().filter(x -> productAppId.equals(x.getProductId())).findFirst().get();
        return product.getName();
    }

    /**
     * 查询设备详细信息
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //从设备表中根据id查询设备信息
        Device device = this.lambdaQuery().eq(Device::getIotId, iotId).one();
        if (device == null) {
            throw new BaseException("没有查到该设备，请重新输入");
        }
        //将设备信息拷贝给vo
        DeviceDetailVo vo = BeanUtil.toBean(device, DeviceDetailVo.class);
        vo.setDeviceSecret(device.getSecret());
        vo.setGmtCreate(device.getCreateTime());
        vo.setRegion(huaWeiIotConfigProperties.getRegionId());
        SysUser user = userService.selectUserById(Long.valueOf(device.getCreateBy()));
        vo.setCreator(user.getUserName());
        //从iot平台上查询详细信息
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);
        try {
            ShowDeviceResponse response = client.showDevice(request);
            if (response == null) {
                throw new BaseException("获取华为云数据详情失败");
            }

            //将信息拷贝给vo
            BeanUtils.copyProperties(response, vo);
            vo.setDeviceStatus(response.getStatus());
            //激活时间，华为云响应的时间格式为字符串类型，需要解析
            String activeTime = response.getActiveTime();
            if (StringUtils.isNotBlank(activeTime)) {
                LocalDateTime gmtActive = OffsetDateTime.parse(activeTime)
                        .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                        .toLocalDateTime();
                vo.setGmtActive(gmtActive);
            }
            if (StringUtils.isNotBlank(response.getFwVersion())) {
                vo.setFirmwareVersion(response.getFwVersion());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("调用华为IO接口查询设备详情失败");
        }
        return vo;

    }

    /**
     * 查看指定产品的已发布物模型中的功能定义详情
     *
     * @param productKey
     * @return
     */
    @Override
    public JSONObject queryProductModelInfo(String productKey) {
        //校验参数
        if (StringUtils.isEmpty(productKey)) {
            throw new BaseException("请输入正确的参数");
        }
        //调用华为云物联网接口
        ShowProductRequest showProductRequest=new ShowProductRequest();
        showProductRequest.setProductId(productKey);
        ShowProductResponse response;

        try {
            response = client.showProduct(showProductRequest);
        } catch (Exception e) {
            throw new BaseException("查询产品详情失败");
        }
        JSONObject jsonObject=null;
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if (CollUtil.isNotEmpty(serviceCapabilities)) {
            jsonObject = JSONUtil.parseObj(serviceCapabilities.get(0));
        }
        return jsonObject;
    }

    /**
     * 查询指定设备的物理模型运行状态
     *
     * @param deviceName
     * @param productKey
     * @return
     */
    @Override
    public Map<String, Object> queryDevicePropertyStatus(String deviceName, String productKey) {
        //根据产品id和设备名称查询
        Device device = lambdaQuery()
                .eq(Device::getDeviceName, deviceName)
                .eq(Device::getProductKey,productKey)
                .one();
        if (device==null) {
            throw new BaseException("未查询到该设备");
        }
        //调用iot平台查询影子信息
        ShowDeviceShadowRequest showDeviceShadowRequest=new ShowDeviceShadowRequest();
        ShowDeviceShadowRequest request = showDeviceShadowRequest.withDeviceId(device.getIotId());
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode()!= HttpStatus.SUCCESS) {
            throw new BaseException("没有上报数据");
        }
        //解析结果
        List<DeviceShadowData> shadow = response.getShadow();
        if (CollUtil.isEmpty(shadow)) {
            throw new BaseException("获取数据失败");
        }
        String eventTime = shadow.get(0).getReported().getEventTime();//格式需要自己手动转换20151212T121212Z
        LocalDateTime reportTime = OffsetDateTime.parse(eventTime, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX"))
                .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();
        List<Map<String,Object>> propertyStatusInfo =new ArrayList<>();
        JSONObject jsonObject = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());
        jsonObject.forEach((k,v) ->{
            String propertKey=k;
            Object propertValue=v;

            Map<String,Object> map=new HashMap<>();
            map.put("identifier",propertKey);
            map.put("value",propertValue);
            map.put("time",reportTime);
            propertyStatusInfo.add(map);
        });
        Map<String,Object> propertyStatusInfoMap = new HashMap<>();
        propertyStatusInfoMap.put("propertyStatusInfo",propertyStatusInfo);

        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("list",propertyStatusInfoMap);


        return resultMap;

    }

    /**
     * 修改设备备注名称
     *
     * @param dto
     */
    @Override
    @Transactional
    public void updateDeviceBrDeviceId(DeviceDto dto) {
        //判断修改的设备是否存在
        Device device = lambdaQuery().eq(Device::getId, dto.getId()).one();
        if (device==null) {
            throw new BaseException("该设备不存在，请确认设备id");
        }
        //在数据库中修改
        device.setBindingLocation(dto.getBindingLocation());
        device.setDeviceDescription(dto.getDeviceDescription());
        device.setDeviceName(dto.getDeviceName());
        device.setLocationType(dto.getLocationType());
        device.setNickname(dto.getNickname());
        device.setPhysicalLocationType(dto.getPhysicalLocationType());
        device.setProductKey(dto.getProductKey());
        device.setRemark(dto.getRemark());
        deviceMapper.updateDeviceById(device);
        //在云端修改
        UpdateDeviceRequest updateDeviceRequest=new UpdateDeviceRequest();
        UpdateDeviceRequest request = updateDeviceRequest.withDeviceId(device.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.withDeviceName(device.getDeviceName());
        body.withDescription(device.getDeviceDescription());
        request.withBody(body);
        UpdateDeviceResponse response = client.updateDevice(request);
        if (response.getHttpStatusCode()!= HttpStatus.SUCCESS) {
            throw new BaseException("云端修改失败，请重新尝试");
        }

    }

    /**
     * 删除设备
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDevice(DeviceDto dto) {
        //根据iotid从数据库中查找设备
        Device device = lambdaQuery()
                .eq(Device::getIotId, dto.getIotId())
                .eq(Device::getProductKey, dto.getProductKey())
                .one();
        if (device==null) {
            throw new BaseException("未查找到该设备，请重新输入");
        }
        //在华为云端删除设备
        try {
            DeleteDeviceRequest deleteDeviceRequest=new DeleteDeviceRequest();
            DeleteDeviceRequest request = deleteDeviceRequest.withDeviceId(device.getIotId());
            DeleteDeviceResponse response = client.deleteDevice(request);
            if (response.getHttpStatusCode()!= HttpStatus.NO_CONTENT&&response.getHttpStatusCode()!=HttpStatus.NOT_FOUND) {
                throw new BaseException("删除数据失败,HTTP响应状态码为"+response.getHttpStatusCode());
            }
        } catch (BaseException e) {
            throw new BaseException("云端删除失败");
        }
        //在数据库中删除设备
        this.removeById(device);
    }


}


